package com.xinbochuang.machine.admin.controller.system;


import cn.hutool.core.date.DateUtil;
import com.xinbochuang.machine.admin.domain.system.SysDept;
import com.xinbochuang.machine.admin.domain.system.SysRole;
import com.xinbochuang.machine.admin.domain.system.SysUser;
import com.xinbochuang.machine.admin.service.system.ISysDeptService;
import com.xinbochuang.machine.common.constant.UserConstants;
import com.xinbochuang.machine.common.controller.BaseController;
import com.xinbochuang.machine.common.utils.SecurityUtils;
import com.xinbochuang.machine.common.utils.ServletUtils;
import com.xinbochuang.machine.common.utils.StringUtils;
import com.xinbochuang.machine.framework.web.domain.AjaxResult;
import com.xinbochuang.machine.framework.web.service.TokenService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.management.relation.RoleInfo;
import java.util.Iterator;
import java.util.List;

/**
 * @author 黄晓鹏
 * @date 2020-09-23
 */
@RestController
@RequestMapping("/system/dept")
public class SysDeptController extends BaseController {
    @Resource
    private TokenService tokenService;
    @Resource
    private ISysDeptService deptService;

    /**
     * 获取部门列表
     */
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list")
    public AjaxResult list(SysDept dept) {
        List<SysDept> deptList = deptService.selectDeptList(dept);
        return AjaxResult.data(deptList);
    }

    /**
     * 查询部门列表（排除节点）
     */
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list/exclude/{deptId}")
    public AjaxResult excludeChild(@PathVariable(value = "deptId", required = false) Integer deptId) {
        List<SysDept> deptList = deptService.selectDeptList(new SysDept());
        deptList.removeIf(d -> d.getDeptId().intValue() == deptId
                || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""));
        return AjaxResult.data(deptList);
    }

    /**
     * 根据部门编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:dept:query')")
    @GetMapping(value = "/{deptId}")
    public AjaxResult getInfo(@PathVariable Integer deptId) {
        return AjaxResult.data(deptService.selectDeptById(deptId));
    }

    /**
     * 获取部门下拉树列表
     */
    @GetMapping("/treeselect")
    public AjaxResult treeselect(SysDept dept) {
        List<SysDept> deptList = deptService.selectDeptList(dept);
        return AjaxResult.data(deptService.buildDeptTreeSelect(deptList));
    }
//    /**
//     * 获取部门下拉树列表
//     */
//    @GetMapping("/treeselectN")
//    public AjaxResult treeselectN(SysDept dept) {
//        SysUser user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
//        List<SysRole> roles = user.getRoles();
//        boolean isSupper=false;
//        for(SysRole sysRole:roles){
//            if(sysRole.getRoleKey().equals("admin")){
//                isSupper=true;
//            }
//        }
//        dept.getParams().clear();
//        if(isSupper){
//            dept.setDeptId(user.getDeptId());
//        }
//        List<SysDept> deptList = deptService.selectDeptList(dept);
//        return AjaxResult.data(deptService.buildDeptTreeSelect(deptList));
//    }


    /**
     * 加载对应角色部门列表树
     */
    @GetMapping(value = "/roleDeptTreeselect/{roleId}")
    public AjaxResult roleDeptTreeselect(@PathVariable("roleId") Integer roleId) {
        List<SysDept> deptList = deptService.selectDeptList(new SysDept());
        AjaxResult ajax = AjaxResult.ok();
        ajax.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
        ajax.put("deptList", deptService.buildDeptTreeSelect(deptList));
        return ajax;
    }

    /**
     * 新增部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:add')")
    @PostMapping
    public AjaxResult add(@RequestBody SysDept dept) {
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
            return AjaxResult.error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        dept.setCreateBy(SecurityUtils.getUsername());
        dept.setCreateTime(DateUtil.now());
        return toAjax(deptService.insertDept(dept));
    }

    /**
     * 修改部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:edit')")
    @PutMapping
    public AjaxResult edit(@RequestBody SysDept dept) {
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
            return AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        } else if (dept.getParentId().equals(dept.getDeptId())) {
            return AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        } else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus())
                && deptService.selectNormalChildrenDeptById(dept.getDeptId()) > 0) {
            return AjaxResult.error("该部门包含未停用的子部门！");
        }
        dept.setUpdateBy(SecurityUtils.getUsername());


        return toAjax(deptService.updateDept(dept));
    }

    /**
     * 删除部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:remove')")
    @DeleteMapping("/{deptId}")
    public AjaxResult remove(@PathVariable Integer deptId) {
        if (deptService.hasChildByDeptId(deptId)) {
            return AjaxResult.error("存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId)) {
            return AjaxResult.error("部门存在用户,不允许删除");
        }
        return toAjax(deptService.deleteDeptById(deptId));
    }

}

